package top.codedance.iotp.client.plugins.sync.http;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.executer.SyncAbstractExecuter;
import top.codedance.iotp.common.entity.PluginResultEntity;

import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

public class HttpExcuterImpl extends SyncAbstractExecuter {
    @Override
    public PluginResultEntity exec(byte[] data, String taskId) {
        PluginResultEntity endResult = new PluginResultEntity();
        JSONObject command = JSONObject.parseObject(new String(data, StandardCharsets.UTF_8));
        String method = command.getString("method").toLowerCase();
        String protocol = command.getString("protocol").toLowerCase();
        String url = command.getString("url");
        String requestBody = command.getString("requestBody");
        JSONObject headers = command.getJSONObject("headers");
        try {
            String result = "";
            Method methoder = null;
            try {
                methoder = HttpRequestUtil.class.getMethod(method, String.class, String.class, String.class, JSONObject.class);
            }catch (Exception e){}
            if(methoder == null){
                methoder = HttpRequestUtil.class.getMethod(method, String.class, String.class, JSONObject.class);
            }
            int parameterCount = methoder.getParameterCount();
            switch(parameterCount){
                case 3:
                    result = (String)methoder.invoke(null, protocol, url, headers);
                    break;
                case 4:
                    result = (String)methoder.invoke(null, protocol, url, requestBody, headers);
                    break;
            }
            endResult.setOk(true);
            endResult.setContext(result);
        }catch (Exception ex){
            endResult.setOk(false);
            endResult.setMsg(ex.getMessage());
        }
        return endResult;
    }
}
